<template>
  <div id="EditAnnouncement">
    <div class="head">
      <div class="tops">
        <div class="title">标题</div>
        <!-- <div>题</div> -->
        <el-input placeholder="请输入内容" v-model="title"></el-input>
      </div>
      <div class="bot">
        <div class="title">通知范围</div>
        <!-- "{ label: 'name', value: 'id', multiple: true, children: 'childrens' }" -->
        <el-cascader popper-class="popperClass" ref="cascaderAddr" collapse-tags :options="options" :props="{ label: 'treeName', value: 'treeId', multiple: true }" clearable v-model="value" @change="handlelog">
          <!-- <template slot-scope="scope">
            <span :id="scope.data.id"></span>
            <img :src="scope.data.icons" style="width: 15px; height: 15px" />
            {{ scope.data.name }}
          </template> -->
        </el-cascader>
      </div>
    </div>
    <div class="content" id="content">
      <div id="editorMenus" class="editorMenus" placeholder="请输入内容"></div>
      <div ref="editor" id="editors" class="editors"></div>
    </div>
    <div class="footer">
      <div class="but">
        <el-button type="info" round @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handlesave(0)" round :loading="saveLoading">保存</el-button>
        <el-button type="primary" @click="handlesave(1)" round :loading="saveLoading">保存并发布</el-button>
      </div>
    </div>
  </div>
</template>
<script>
import E from "wangeditor";
import serveUrl from "@/config/serverAddress"; // 导入接口域名列表
import { mapState } from "vuex";
import { mapTreeAddIcon } from "@/util/util";
export default {
  name: "EditAnnouncement",
  data() {
    return {
      saveLoading: false,
      // 标题内容
      title: "",
      // 富文本域数据
      value2: "",
      editors: {},
      // 富文本内容
      texts: "",
      noticeRangeDtos: [],
      isClear: false,
      detail: "",
      // 多选框
      value: [],
      options: [],
      companyArr: [],
      depmArr: [],
      noticeid: "", // 公告id
      filterText: "",
      treeData: [],
      defaultProps: {
        children: "childrens",
        label: "name",
      },
    };
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  mounted() {
    this.handle();
  },
  computed: {
    ...mapState({
      uif: (state) => state.common.uif,
      userInfo: (state) => state.common.userInfo,
      tagCurrent: (state) => state.tag.tagCurrent,
    }),
  },
  methods: {
    // 富文本编译
    handle() {
      let editor = new E("#editorMenus", this.$refs.editor);
      // editor.txt.clear()
      this.editors = editor;
      console.log(this.editors.config, "this.editors.getconfig();");
      let excludeKeys = ["link", "video"];
      excludeKeys.forEach((m) => {
        let menuIndex = this.editors.config.menus.findIndex((menu) => menu == m);
        this.editors.config.menus.splice(menuIndex, 1);
      });
      // this.editors.config.menus = [];
      let that = this;
      // change发生改变触发
      editor.config.onchange = function (newHtml) {
        that.texts = newHtml;
      };
      editor.config.uploadImgMaxLength = 10; // 一次最多上传 1 个图片
      // 添加图片文件时，自定义第一个参数。
      editor.config.uploadImgServer = serveUrl.cs + "/Common/uploadMultipleFile";
      editor.config.uploadFileName = "formFile";
      // 上传图片时添加 http 请求的 header 。
      editor.config.uploadImgHeaders = {
        Authorization: this.uif,
        Accept: "application/json, text/plain, */*",
      };
      // 配置 server 接口地址
      // 上传图片时可自定义传递一些参数
      editor.config.uploadImgParams = {
        fileTypeName: "img",
      };
      // 如果需要将参数拼接到 url 中，可再加上如下配置。
      editor.config.uploadImgParamsWithUrl = true;
      // 失去焦点触发
      editor.config.onblur = function (newHtml) {
        // console.log('onblur', newHtml) // 获取最新的 html 内容
        that.texts = newHtml;
      };
      editor.config.uploadImgHooks = {
        // 上传图片之前
        before: function () {
          // console.log(xhr)
        },
        // 图片上传并返回了结果，图片插入已成功
        success: function () {
          // console.log(xhr)
          this.$message({
            type: "success",
            message: "插入图片失败",
          });
        },
        // 图片上传并返回了结果，但图片插入时出错了
        fail: function () {
          this.$message({
            type: "error",
            message: "插入图片失败",
          });
        },
        // 上传图片出错，一般为 http 请求的错误
        error: function () {
          this.$message({
            type: "error",
            message: "上传图片错误",
          });
        },
        // 上传图片超时
        timeout: function () {
          this.$message({
            type: "error",
            message: "上传图片超时",
          });
        },
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function (insertImgFn, result) {
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          for (let i = 0; i < result.data.length; i++) {
            insertImgFn(result.data[i].fileUrl);
          }
        },
      };
      this.$nextTick(() => {
        if (editor == null) {
          editor.create();
        } else {
          editor.destroy(); // 这里做了一次判断，判断编辑器是否被创建，如果创建了就先销毁。
          editor.create();
        }
      });
    },
    // 通告范围选择事件
    handlelog() {
      let nodesInfo = this.$refs["cascaderAddr"].getCheckedNodes();
      var companys = [];
      var ds = [];
      var users = [];
      let arr = [];

      nodesInfo.forEach((item) => {
        // eslint-disable-next-line eqeqeq
        if (item.data.range == 0 || item.data.range == 1) {
          companys.push(item.data);
          // eslint-disable-next-line eqeqeq
        } else if (item.data.range == 2) {
          ds.push(item.data);
        } else {
          users.push(item.data);
        }
      });
      companys.forEach((element) => {
        var subid = element.subid;
        ds = ds.filter((item) => subid !== item.subid);
        users = users.filter((item) => subid !== item.subid);
        arr.concat(companys, ds, users);
      });
      ds.forEach((element) => {
        var departmentid = element.departmentid;
        users = users.filter((item) => departmentid !== item.departmentid);
        arr.concat(companys, ds, users);
      });
      arr = [...companys, ...ds, ...users];
      let params = [];
      arr.map((item) => {
        let obj = {};
        obj.dataId = [{ dataId: item.treeId, subId: item.subid }];
        obj.range = item.range;
        params.push(obj);
      });
      console.log(params, "params");
      this.noticeRangeDtos = params;
    },
    // 取消
    handleCancel() {
      this.$store.commit("DEL_TAG", this.tagCurrent);
      this.$router.go(-1);
      this.value = [];
    },

    // 保存
    async handlesave(type) {
      try {
        this.saveLoading = true;
        if (this.value.length <= 0) {
          this.$message.warning("请选择通知范围");
          return;
        }
        if (!this.title) {
          this.$message.warning("请输入标题");
          return;
        }
        if (!this.texts) {
          this.$message.warning("请编辑内容");
          return;
        }

        let params = {
          notice: {
            type: 2,
            title: this.title,
            content: this.texts,
            subid: "00000000-0000-0000-0000-000000000000",
            // subid: this.userInfo.subid,
            status: type,
          },
          noticeRangeDtos: this.noticeRangeDtos,
        };
        let message = type == 1 ? "发布成功" : "保存成功";
        if (this.$route.query.id !== undefined) {
          params.notice.id = +this.$route.query.id;
          const ret = await this.$api.Announcement.getEditAnnouncement(params);
          if (ret.data.status === 200) {
            this.$message({
              type: "success",
              message: message,
            });
            this.handleCancel();
          }
        } else {
          const ret = await this.$api.Announcement.getAnnouncement(params);
          if (ret.data.status === 200) {
            this.$message({
              type: "success",
              message: message,
            });
            this.handleCancel();
          }
        }
      } finally {
        this.saveLoading = false;
      }
    },

    async handleSub1() {
      const { data } = await this.$api.publicApi.GetSubCompanyView();
      this.treeData = JSON.parse(JSON.stringify(mapTreeAddIcon(this.handleData([data.data]))));
      this.options = this.treeData[0].childrens;
      if (this.$route.query.id) {
        this.noticeid = this.$route.query.id;
        this.handleList();
      }
    },

    handleData(data, parentObj = {}) {
      // 关联父子数据  1   1-1   1-1-1    1-1-1-1   n-n-n-n
      data.map((item, index) => {
        if (parentObj.relatedId) {
          item.relatedId = parentObj.relatedId + `-${index + 1}`;
        } else {
          item.relatedId = index + 1 + "";
        }
        if (item.childrens && item.childrens.length) {
          this.handleData(item.childrens, item);
        } else {
          delete item.childrens;
        }
      });
      return data;
    },
    // 获取子公司列表
    async handleSub() {
      const ret = await this.$api.Announcement.getNotificationRange();
      // console.clear()
      let data = ret.data.data;
      data.forEach((item) => {
        item.range = 1;
      });
      this.options = data;

      // 公司
      this.handleCompanyArr(data);
      // 部门
      this.companyArr.forEach((item) => {
        item.children = [];
        this.depmArr = [];
        this.handleDepmArr(item.departmentList);
        item.children.push(...this.depmArr);
      });
      // 职员
      this.companyArr.forEach((item) => {
        item.children.forEach((item1) => {
          item1.children = item1.userList;
        });
      });
      // 修改字段名称 treeName  treeId  1.companyid  2.depm...id   3.userid
      this.editTreeAttr(this.companyArr);
      // 解决子级为空[]  父级无法选中
      this.getTreeData(this.companyArr);

      if (this.$route.query.id) {
        this.noticeid = this.$route.query.id;
        this.handleList();
      }
    },
    // 如果子集为空 就不显示
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if ("children" in data[i]) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
      }
      return data;
    },

    editTreeAttr(data) {
      data.map((item) => {
        // 0集团 1子公司 2部门 3员工
        if (item.range <= 1) {
          item.treeName = item.abbreviationName;
          item.treeId = item.subid;
        }
        if (item.range === 2) {
          item.treeName = item.departmentName;
          item.treeId = item.departmentid;
        }
        if (item.range === 3) {
          item.treeName = item.userName;
          item.treeId = item.userid;
        }
        if (item.children) {
          this.editTreeAttr(item.children);
        }
      });
    },

    handleCompanyArr(data, level = 1) {
      data.map((item) => {
        item.level = level;
        for (let i = 0; i < item.level; i++) {
          item.abbreviationName = "    " + item.abbreviationName;
        }
        this.companyArr.push(item);
        if (item.subList) {
          this.handleCompanyArr(item.subList, level + 1);
        }
      });
    },
    handleDepmArr(data, level = 1) {
      data.map((item1) => {
        item1.level = level;
        for (let i = 0; i < item1.level; i++) {
          item1.departmentName = "    " + item1.departmentName;
        }
        this.depmArr.push(item1);
        if (item1.childrenList) {
          this.handleDepmArr(item1.childrenList, level + 1);
        }
      });
    },

    // 数据反填获取数据
    async handleList() {
      this.$loading();
      const ret = await this.$api.Announcement.getSingleAnnouncement({ id: this.noticeid });
      let resData = ret.data.data;
      this.title = resData.notice.title;
      this.value2 = resData.notice.content;
      this.noticeRangeDtos = resData.noticeRangeDtos;
      this.setValue(resData.noticeRangeDtos);
      this.editors.txt.html(`${this.value2}`);
      this.$loading().close();
    },

    getdataId(dataId, companyArr) {
      let itemdata = companyArr.find((item) => {
        // eslint-disable-next-line eqeqeq
        return item.treeId == dataId;
      });
      if (itemdata) {
        this.itemdata = itemdata;
      } else {
        companyArr.map((item) => {
          if (item.children) {
            this.getdataId(dataId, item.children);
          }
        });
      }
    },
    setValue(noticeRangeDtos) {
      let value = [];
      noticeRangeDtos.map((item) => {
        this.getdataId(item.dataId[0].dataId, this.companyArr);
        let arr = [];
        switch (item.range) {
          case 0:
            this.itemdata.children.map((item) => {
              if (item.children) {
                item.children.map((i) => {
                  let children = JSON.parse(JSON.stringify(i));
                  arr.push([children.subid, children.departmentid, children.treeId]);
                });
              } else {
                arr.push([item.subid, item.departmentid]);
              }
            });
            value = [...value, ...arr];
            break;
          case 1:
            if (this.itemdata.children !== undefined) {
              this.itemdata.children.map((item) => {
                if (item.children) {
                  item.children.map((i) => {
                    let children = JSON.parse(JSON.stringify(i));
                    arr.push([children.subid, children.departmentid, children.treeId]);
                  });
                } else {
                  arr.push([item.subid, item.departmentid]);
                }
              });
            } else {
              arr.push([this.itemdata.subid]);
            }

            value = [...value, ...arr];
            break;
          case 2:
            if (this.itemdata.children !== undefined) {
              this.itemdata.children.map((children) => {
                arr.push([this.itemdata.subid, this.itemdata.treeId, children.treeId]);
              });
            } else {
              arr.push([this.itemdata.subid, this.itemdata.departmentid]);
            }
            value = [...value, ...arr];
            break;
          case 3:
            arr.push([this.itemdata.subid, this.itemdata.departmentid, this.itemdata.treeId]);
            value = [...value, ...arr];
            break;
          default:
            break;
        }
      });
      this.value = value;
    },
  },
  activated() {
    this.value = [];
    this.handleSub();
    this.title = "";
    this.editors.txt.html("");
    this.companyArr = [];
  },
  created() {
    this.value = [];
  },
};
</script>
<style lang="less">
.el-cascader-node__label {
  white-space: pre !important;
}
#EditAnnouncement {
  width: 100%;
  height: 100%;
  position: relative;
  background-color: #f5f6fa !important;
  .head {
    padding-top: 10px;
    padding-bottom: 10px;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 0 10px 0 #ccc;
    .el-input--small .el-input__inner {
      width: 300px !important;
    }
    .el-select {
      width: 300px;
    }
    .el-cascader__tags .el-tag .el-icon-close {
      display: none !important;
    }
    .title {
      text-align-last: justify;
      text-align: justify;
      width: 75px;
      margin: 0px 10px 0 20px;
      color: #999bab;
    }
    .tops {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      .title {
        width: 84px;
      }
    }
    .bot {
      display: flex;
      margin-top: 20px;
    }
  }
  .content {
    margin-top: 20px;
    border-radius: 10px;
    background-color: #fff;
    margin-bottom: 55px;
    .editorMenus {
      border-radius: 10px 10px 0 0;
      box-shadow: 0 0 10px 0 #ccc;
    }
    .w-e-toolbar {
      border-radius: 10px;
      z-index: 3 !important;
    }
    .w-e-text-container {
      z-index: 0 !important;
    }
    .editors {
      border-radius: 10px;
      box-shadow: 0 0 10px 0 #ccc;
      margin-top: -1px; //将多出来的一像素边框隐藏
      // border: 1px solid #ccc;
      min-height: 300px; //编辑框最小高度
      height: auto; //编辑框高度超过最小高度会根据内容高度自适应
      .w-e-text {
        height: 350px !important;
      }
    }
  }
  .footer {
    width: 100%;
    position: absolute;
    height: 50px;
    left: 0;
    bottom: 0;
    background-color: #fff;
    border-radius: 10px;
    .but {
      position: absolute;
      left: 50%;
      bottom: 50%;
      transform: translate(-50%, 50%);
    }
  }
}
</style>
